var $el = $('.input-group'),
    $touristInfo = $('#touristInfo'),
    $adultNum = $('#adultNum'),
    $childNum = $('#childNum'),
    $orderInfo = $('#orderInfo'),
    //记录订单总人数
    orderPeopleNum = 0;
// $('input[type="number"]:disabled').prop('disabled', false);


// 点击票数增加按钮

$el.on('click', '.plus', function(){
    $(this).prev().val(parseInt( $(this).prev().val() ) + 1);
})


  // 点击票数减少按钮

$el.on('click', '.down', function(){
    var num = parseInt($(this).next().val()) - 1 ;
    if(num<0) num = 0;
    $(this).next().val(num);
})


  // 购买票数不能小于0

$el.on('change', '.text-center', function(){
    if( parseInt($(this).val()) < 0 )
        $(this).val(0);
})

//添加游客
function addTourist(){
    var index = $('.tourist-info').length;
    var html = ' <tr class="tourist-info">\
                        <td>'+(parseInt(index)+1)+'</td>\
                        <td class="add delete">-</td>\
                        <td><input type="radio" value="'+index+'" name="tourist[contenct]"/></td>\
                        <td class="clearfix">\
                            <div class="col-xs-12 text-left">\
                                <label for="" class="col-xs-4">姓名</label>\
                                <div class="col-xs-8"><input type="text"  required name="tourist['+index+'][name]" class="form-control touristName" /></div>\
                                <label for="" class="col-xs-4">性别</label>\
                                <div class="col-xs-8">\
                                    <select  name="tourist['+index+'][sex]">\
                                        <option value="1">男</option>\
                                        <option value="2">女</option>\
                                    </select>\
                                </div>\
                                <label for="" class="col-xs-4">年龄</label>\
                                <div class="col-xs-8">\
                                    <select  name="tourist['+index+'][tourists_type]">\
                                        <option value="1">成人</option>\
                                        <option value="3">小孩</option>\
                                    </select>\
                                </div>\
                                <label for="" class="col-xs-4">证件</label>\
                                <div class="col-xs-8">\
                                    <select  name="tourist['+index+'][documents_type]">\
                                        <option value="1" selected>身份证</option>\
                                    </select>\
                                </div>\
                                <label for="" class="col-xs-4">证件号</label>\
                                <div class="col-xs-8"><input type="number" name="tourist['+index+'][documents_num]"  min="0"   class="form-control card" /></div>\
                                <label for="" class="col-xs-4">手机号码</label>\
                                <div class="col-xs-8"><input type="number" name="tourist['+index+'][tourists_phone]"  min="0"  class="form-control phone" /></div>\
                                <label for="" class="col-xs-4">游客地址</label>\
                                <div class="col-xs-8"><input type="text" name="tourist['+index+'][tourists_address]"    class="form-control " /></div>\
                            </div>\
                        </td>\
                        <td>\
                            <textarea rows="10" name="tourist['+index+'][tourists_remarks]" class="form-control"></textarea>\
                        </td>\
                    </tr>';
    $touristInfo.append(html);
}

var phonePreg = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/,
    cardPreg  = /\d/;
    // cardPreg = /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/;

  // 监控身份证输入
$touristInfo.on('change', '.card', function(){
    if( !cardPreg.test($(this).val()) ){
        layer.msg('身份证格式错误');
        $(this).focus();
    }
})

  // 监控手机号码输入
$touristInfo.on('change', '.phone', function(){
    if( !phonePreg.test($(this).val()) ){
        layer.msg('手机号码格式错误');
        $(this).focus();
    }
})

  // 监控游客信息删除按钮
$touristInfo.on('click', '.delete', function(){
    var $that = $(this)
    var page = layer.confirm('确认删除此游客信息',function(index){
        layer.close(page)
        $that.closest('tr').remove();
    })
})

//点击确认人数按钮
$('#confirmPeopelNum').on('click', function(){
    var $that = $(this);
    var index = layer.confirm('成人：'+ $adultNum.val() +' & 儿童：'+ $childNum.val() /*+' / 老人：'+ $oldNum.val()*/ ,
        {btn:['确认人数', '取消']},
        function(){
            $that.off('click');
            $that.attr('disabled', true);
            $el.off('click', '.plus');
            $el.off('click', '.down');
            orderPeopleNum = parseInt($adultNum.val()) + parseInt($childNum.val()) /*+ parseInt($oldNum.val())*/;
            $adultNum.prop('readonly', true);
            $childNum.prop('readonly', true);
            $('#submit').prop('disabled', false);
            $('#discounts').prop('disabled', false);
            $('input[type="number"]:disabled').prop('disabled', false);
            $('#touristInfo').find('input[type="text"]:disabled').prop('disabled', false);
            $('#touristInfo').find('select:disabled').prop('disabled', false);
            $('#add').on('click', function(){
                addTourist();
            });
            $('.add-room-btn').prop('disabled', false);
            layer.close(index);
            changeOrderPrice();
    })
})

//来回交通方式升级座位数量监控
$('.seats-go,.seats-back').on('change', function(){
    var $el = $(this).closest('.traffic-warp'),
    num = 0;
    $el.find('input[type="number"]').each(function(i, n){
        num += parseFloat( $(n).val() || 0 );
    })
    if( num > parseFloat( $(this).data('max') ) ){
        layer.alert('余位不足', {icon: 5});
        $(this).val(0);
        $(this).focus();
        return false;
    }
    changeOrderPrice();
});



//可升级酒店房间数量变动
$('.up-hotel').on('change', function(){
    if( $(this).val() > parseInt( $(this).data('max') ) ){
        layer.alert('剩余房间数量不足', {icon: 5});
        $(this).focus();
        $(this).val(0);
        return false;
     } else if( $(this).val() < 0 ){
        $(this).val(0)
     }
     changeOrderPrice();
})

/**
 * 点击添加房间的按钮
 * @param {[obj]} obj [被点击的按钮指针]
 */
function addRoom(obj){
    var $el = $(obj).closest('.hotel-warp'),
        $standardHotel = $el.closest('.standard-hotel'),
        $hotel = $el.find('.hotel'),
        roomMaxNum = parseInt( $hotel.val()*1 + ($standardHotel.find('.new-hotel').length || 0) ) + 1;
    //检测房间数量是否超标
    if( roomMaxNum > parseInt( $hotel.data('max') ) ){
        layer.alert('房间数量不足', {icon: 5});
        return;
    }
    var $elClone = $el.clone();
    $elClone.find('.add-room').attr({'class': 'btn btn-danger', 'onclick': 'removeRoom(this)'}).html('删除');
    $elClone.find('.notes').html('填写入住人数').addClass('text-danger');
    //新增的房间更改类
    var $hotelInput = $elClone.find('.hotel'),
        name = $hotelInput.attr('name').replace('hotel', 'new_hotel')+'[]';
    $hotelInput.removeClass('hotel').addClass('new-hotel').attr('name', name).val('');
    $standardHotel.append($elClone);
    changeOrderPrice();
}

/**
 * 点击删除房间的按钮
 * @param {[obj]} obj [被点击的按钮指针]
 */
function removeRoom(obj){
    var index = layer.confirm('确定删除该房间信息?', {btn: ['确认', '取消']}, function(){
        addRoomPriceFun($(obj), 'isDel')
    })
}


//标准房间数量变动
$('.hotel').on('change', function(){
    var $standardHotel = $(this).closest('.standard-hotel'),
        roomMaxNum = parseInt( $(this).val() ) + parseInt( ($standardHotel.find('.new-hotel').length | 0) );
    if( roomMaxNum > parseInt( $(this).data('max') ) ){
        layer.alert('房间余位不足', {icon: 5});
        $(this).val(0);
        $(this).focus();
    }
    changeOrderPrice();
})

//新增房间人数变动 ———— 补房差
$('#orderInfo').on('change', '.new-hotel', function(){
    //房间最大容纳人数
    var uNum = parseInt( $(this).data('unum') ),
        peopleNum  = parseInt($(this).val());
    if( peopleNum > uNum ){
        $(this).val(0);
        layer.alert('该房间最大可入住人数：'+uNum, {icon: 5});
        return false;
    }
    if( peopleNum <= 0){
        layer.alert('房间最少需要入住1人', {icon: 5});
        $(this).val(1);
    }
    //计算当天补房差
    addRoomPriceFun($(this), '');
})

/**
 * 计算补房差
 * @param {[obj]}    $obj [jq对象 change的.new-hotel]
 * @param {[string]} type []
 */
function addRoomPriceFun($obj, type){
    /*更改当天补房差价格*/
    var $dayHotel = $obj.closest('.day-hotel'),
        price = 0; //当前需要补房差的价格

    if(type == 'isDel'){
        $obj.closest('.hotel-warp').remove();
        layer.closeAll()
    }

    $dayHotel.find('.new-hotel').each(function(i, n){
        if( parseInt( $(n).data('unum') ) > ( $(n).val() || 0)*1 )
            price += ( ($(n).val() || 0)*1) * addRoomPrice;
    })
    $dayHotel.find('.addPrice').text(price.toFixed(2));
    /*更改订单价格*/
    changeOrderPrice();
}


//订单价格变动
function changeOrderPrice(){
    //基础价格
    var base = parseFloat( $('#adultBase').html() ) * $('#adultNum').val() + parseFloat( $('#childBase').html() ) * $('#childNum').val() ;

    // console.log('step1:' + base);
    //交通(去)升级费用
    $('#upGoTraffic').find('.seats-go').each(function(i, n){
        base += parseFloat( $(n).data('price') ) * ($(n).val() || 0);
    })

    // console.log('交通(去)升级费用:' + base);
    //交通(回)升级费用
    $('#upBackTraffic').find('.seats-back').each(function(i, n){
        base += parseFloat( $(n).data('price') ) * ($(n).val() || 0);
    })
    // console.log('交通(回)升级费用:' + base);
    //标准酒店补房差
    $orderInfo.find('.addPrice').each(function(i, n){
        base += parseFloat( $(n).html() );
    })
    // console.log('标准酒店补房差:' + base);

    //酒店升级服务
    $orderInfo.find('.up-hotel').each(function(i, n){
        base += $(n).data('actual') * ($(n).val() || 0 );
    })
    // console.log('酒店升级服务:' + base);
    //优惠券选择
    base -= $('#discounts').val() || 0;
    // console.log('优惠券选择:' + base);
    $('#orderTotalPrice').html(base.toFixed(1));
}
//姓名验证正则
var namePreg = /[^\w\d\u4E00-\u9FA5]/ig;
//点击支付
$('#submit').on('click', function(){
    var $el = $('#touristInfo').find('.tourist-info');
    var flag = 1;
    if( parseInt( $el.length) < orderPeopleNum ){
        layer.alert('游客数量不匹配', {icon: 5});
        return false;
    }
    $el.each(function(i, n){
        var val = $(n).find('.touristName').val();
        if( !val || namePreg.test(val)){
            layer.alert('游客姓名由数字、字母、中文组成', {icon: 5});
            $(n).focus();
            flag = 0;
            return false;
        }
    })

    if(flag == 0) return;
    var index = layer.confirm('确定支付?',{btn:['确定','取消']}, function(){

        var param = $('#form').serialize();
        $.post('/Reseller/OrderCenter/submitTouristInfo', param, function(data){
            layer.close(index);
            // layer.alert(data['msg'], {icon: data['status'] == 1? 6:5});
            if(data['status'] == 1){
                layer.alert('下单成功', {icon:  6});
                setTimeout(function(){
                    location.href = '/Reseller/OrderCenter/detailView/order_id/'+data['order_id'];
                }, 1000);
            }else if(data['status'] == 4){
                layer.alert(data['msg'], {icon:  5});
            }else{
                layer.alert('下单失败', {icon:  5});
            }
            $('#verify').click();
        },'json')
    })
})